package com.baijiaoxi.utils.qcloud;

import com.baijiaoxi.common.utils.jdk.Strings;
import com.tencentcloudapi.ocr.v20181119.models.BusinessCardInfo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TencentOCRResult {
    protected Map<String, List<BusinessCardInfo>> fieldMap;

    public TencentOCRResult(BusinessCardInfo[] businessCardInfos) {
        this.fieldMap = Arrays.stream(businessCardInfos).parallel().collect(Collectors.groupingBy(BusinessCardInfo::getName));
    }

    public String getFieldValue(TencentBusinessCardField tencentBusinessCardField) {
        return getFieldValue(false, tencentBusinessCardField);
    }

    public String getFieldValue(boolean appendName, TencentBusinessCardField tencentBusinessCardField) {
        List<BusinessCardInfo> businessCardInfoList = fieldMap.get(tencentBusinessCardField.getValue());
        return businessCardInfoList == null || businessCardInfoList.isEmpty() ? "" :
                (
                        (appendName ? tencentBusinessCardField.getValue() : "") +
                                String.join(",", businessCardInfoList.parallelStream().map(BusinessCardInfo::getValue)
                                        .filter(val -> !Strings.isNullOrEmpty(val))
                                        .collect(Collectors.toList()))
                );
    }

    public String getFieldValue(TencentBusinessCardField... tencentBusinessCardFields) {
        return getFieldValue(false, tencentBusinessCardFields);
    }

    public String getFieldValue(boolean appendName, TencentBusinessCardField... tencentBusinessCardFields) {
        return String.join(",", Arrays.stream(tencentBusinessCardFields).parallel()
                .map(tencentBusinessCardField -> getFieldValue(appendName, tencentBusinessCardField))
                .filter(val -> !Strings.isNullOrEmpty(val))
                .collect(Collectors.toList()));
    }
}
